//
//  XJUserAccountModel.swift
//  新浪微博
//
//  Created by 徐绩 on 16/4/19.
//  Copyright © 2016年 ayumi. All rights reserved.
//

import UIKit
import SVProgressHUD


class XJUserAccountModel: NSObject {
    
    //单例
    static let sharedModel: XJUserAccountModel = XJUserAccountModel()
    
    var account: XJUserAccount?
    
    //初始化的时候,尝试去沙盒中读取数据
    override init() {
        super.init()
        
        self.account = self.accountInSandbox()
    }
    
    var accessToken: String? {
    
        return self.account?.access_token
    }
    
    //判断当前用户是否登录 : 1.判断是否有accessToken  2.判断accessToken是否过期
    var islogin: Bool {
        if accessToken == nil {
        
            return false
        }
        //取过期时间和当前时间进行对比
        guard let expiredDate = self.account?.expiresDate else{
            return false
        }
        //当前时间比过期时间大,没过期
        if NSDate().compare(expiredDate) == .OrderedAscending {
        
            return true
        }
        return false
    }
    
    
    // MARK: - 加载AccessToken
    func loadAccessToken(code: String, finished: (isSuccess: Bool)->()) {
        
        let url = "https://api.weibo.com/oauth2/access_token"
        
        let param = [
            
            "client_id": APP_KEY,
            "client_secret": APP_SECRET,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": REDIRECT_URI
            
        ]
        
        XJNetworkTools.sharedTools.request(.Post, url: url, parameters: param) { (responseObject, error) -> () in
            
            if error != nil {
                print(error)
                finished(isSuccess: false)
                return
            }
            //            print("请求成功\(responseObject)")
            guard let dict = responseObject as? [String: AnyObject] else {
                finished(isSuccess: false)
                return
            }
            //字典转模型
            let account = XJUserAccount(dict: dict)
            
            // accessToken 获取到了，获取个人信息
           self.loadUserInfo(account, finished: finished)
        }
        
    }
    // MARK: - 获取个人信息,文档中找接口数据
    func loadUserInfo(account: XJUserAccount,finished: (isSuccess: Bool)->()){
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        //参数
        let param = [
            "access_token": account.access_token ?? "",
            "uid": account.uid ?? ""
            
        ]
        //发送请求
        XJNetworkTools.sharedTools.request(.Get, url: urlString, parameters: param) { (responseObject, error) -> () in
            
            if error != nil {
                
                SVProgressHUD.showErrorWithStatus("网络错误")
                finished(isSuccess: false)
                return
            }
            
            guard let dict = responseObject as? [String: AnyObject] else{
                finished(isSuccess: false)
                return;
            }
            account.name = dict["name"] as? String
            account.avatar_large = dict["avatar_large"] as? String
            
            self.account = account
            self.saveUserInfo(account)
            
            finished(isSuccess: true)
        }
    }
    
    // MARK: - 归档用户信息
    private func saveUserInfo(account: XJUserAccount) {
        
        //归档路径 document路径 + 文件名
        let path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory,NSSearchPathDomainMask.UserDomainMask , true).last! as NSString).stringByAppendingPathComponent("account.archive")
        
        //归档
        NSKeyedArchiver.archiveRootObject(account, toFile: path)
    }
    
    
    // MARK: - 解档用户信息
    private func accountInSandbox() -> XJUserAccount? {
        
        //解档路径
        let path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory,NSSearchPathDomainMask.UserDomainMask , true).last! as NSString).stringByAppendingPathComponent("account.archive")
        
        //解档
        let result = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? XJUserAccount
        
        return result
    }
 
}
